# -*- coding: utf-8 -*-
from . import BaseController
from backend.models import Operator, Role, Resource, AuthUser
from django.contrib.auth.signals import user_logged_in
from backend.libs import myjson as json
from hashlib import md5


class Login(BaseController):
    def post(self):
        data = json.loads(self.request.body)
        password = data.get('password')
        username = data.get('username')
        if not username or not password:
            return self.render_json(code=-1, msg='无效的用户名或密码')
        user = AuthUser.objects.filter(username=data.get('username')).first()
        if not user or not user.check_password(password):
            self.render_json(code=-1, msg='无效的用户名或密码')
        elif not user.is_active:
            self.render_json(code=-1, msg='用户被锁定')
        else:
            user_logged_in.send(sender=user.__class__, user=user)
            return self.render_json(data=user.to_login_dict())


class Logout(BaseController):
    def post(self):
        # to-do: 实现用户token的删除操作
        return self.render_json()


class UserInfo(BaseController):
    def get(self):
        current_user = self.current_user
        if not current_user:
            return self.render_json(code=50008, msg='非法的token')
        return self.render_json(data=current_user.to_user_info_dict())


class Signin(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        print('登录数据--{}'.format(data))
        m2 = md5()
        m2.update(data.get('password').encode("utf-8"))
        data['password'] = m2.hexdigest()
        opt = Operator.objects.filter(**data).first()
        if not opt:
            self.render_json(code=-1, msg='用户名或密码错误')
        elif opt.is_disable:
            self.render_json(code=-1, msg='用户被锁定')
        else:
            return self.render_json(data=opt.to_dict())


class LeftNav(BaseController):

    def get(self):
        op = self.current_user
        roles = op.role_set.all()
        if not roles:
            return self.render_json(data = { 'menus': [] } )    

        resource_ids = []
        for role in roles:
            tmp_resource_ids = [ r.id for r in role.resources.all() ]
            resource_ids = resource_ids + tmp_resource_ids
        if not resource_ids:
            return self.render_json(data = { 'menus': [] } )

        menus = Resource.to_menu(resource_ids)

        return self.render_json(data = { 'menus': menus } )